package org.hishenframework.core.data.jdbc.template;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import org.springframework.jdbc.core.JdbcTemplate;

public class HishenSimpleJdbcDelete {

	private String tableName;
	private JdbcTemplate jdbcTemplate;
	
	public HishenSimpleJdbcDelete(JdbcTemplate jdbcTemplate) {
		this.jdbcTemplate = jdbcTemplate;
	}
	
	public HishenSimpleJdbcDelete withTableName(String tableName) {
		this.tableName = tableName;
		return this;
	}
	
	public int execute(Map<String, Object> args) {
		StringBuilder sql = new StringBuilder("DELETE FROM ");
		sql.append(tableName).append(" WHERE ");
		List<Object> params = new ArrayList<>();
		for (Entry<String, Object> entry : args.entrySet()) {
			sql.append(entry.getKey()).append(" = ? AND ");
			params.add(entry.getValue());
		}
		sql.delete(sql.length() - 5, sql.length());
		int count = jdbcTemplate.update(sql.toString(), 
						params.toArray(new Object[params.size()])
					);
		return count;
	}
}
